package com.edgar.download.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.edgar.download.Download;

import java.util.ArrayList;
import java.util.List;

import static com.edgar.download.database.Downloads.DownloadImpl;

/**
 * Created by dell on 2015/9/25.
 */
public class DownloadHelp{
    private DownloadDataBaseHelp mDownloadDataBaseHelp;

    public DownloadHelp(Context context){
        mDownloadDataBaseHelp = DownloadDataBaseHelp.getInstance(context);
    }

    public List<Download> queryAllDownload() {
        SQLiteDatabase database = mDownloadDataBaseHelp.getDataBase();
        Cursor cursor = null;
        List<Download> downloads = null;
        try {
            cursor = database.rawQuery("SELECT * FROM " + DownloadImpl.TAB_NAME, null);
            downloads = new ArrayList<Download>();
            cursor.moveToFirst();
            while (cursor.moveToNext()) {
                downloads.add(Download.createDownload(cursor));
                if (cursor.isAfterLast()) {
                    break;
                }
            }
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return downloads;
    }

    public long insertDownloadToDb(ContentValues contentValues){
        SQLiteDatabase database = mDownloadDataBaseHelp.getDataBase();
        long id = database.insert(DownloadImpl.TAB_NAME,null,contentValues);
        return id;
    }

    /** 更新下载 **/
    public int updateDownloadWithId(ContentValues contentValues,long id){
        SQLiteDatabase database = mDownloadDataBaseHelp.getDataBase();
        return database.update(DownloadImpl.TAB_NAME, contentValues,
                DownloadImpl._ID+"=?",new String[]{""+id});
    }

    public int deleteDownloadWithId(long id){
        SQLiteDatabase database = mDownloadDataBaseHelp.getDataBase();
        return database.delete(DownloadImpl.TAB_NAME, DownloadImpl._ID + "=?", new String[]{"" + id});
    }

    public int clearDownloadDb(){
        SQLiteDatabase database = mDownloadDataBaseHelp.getDataBase();
        return database.delete(DownloadImpl.TAB_NAME,null,null);
    }
}